package com.ztesoft.book.common.utils.mail;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.google.common.base.Charsets;
import com.ztesoft.book.common.constant.CommonParamUtil;
import com.ztesoft.book.common.utils.exception.ExUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.util.ByteArrayDataSource;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;


/**
 * @Description 邮件工具类
 * @Author YangFan
 * @Date 2021-06-22 17:26
 */
@Slf4j
@Component
public class MailUtils {

//    @Value("${spring.mail.host}")
    private String host;

//    @Value("${spring.mail.username}")
    private String username;

//    @Value("${spring.mail.password}")
    private String password;

//    @Value("${spring.mail.port}")
    private Integer port;

//    @Value("${spring.mail.properties.mail.smtp.socketFactoryClass}")
    private String socketFactoryClass;

    private static ExecutorService executor = ThreadUtil.newExecutor(5);


    /**
     * 方法功能描述:
     * < 发送带附件邮件，须配合线程池调用，否则大文件发送会阻塞很长时间 >
     *
     * @return void
     * @author YangFan
     * @date 2021-07-25 15:37
     */
    public void sendAttachFileMail(String title, String target, String content, String path) {
        executor.execute(() -> {
            log.info("当前执行邮件发送线程：" + Thread.currentThread().getName());
            String extName = StringUtils.getFilenameExtension(path);
            HttpURLConnection httpConn = null;
            try {
                // 创建url对象
                URL urlObj = new URL(path);
                // 创建HttpURLConnection对象，通过这个对象打开跟远程服务器之间的连接
                httpConn = (HttpURLConnection) urlObj.openConnection();
                httpConn.setDoInput(true);
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(5000);
                httpConn.connect();
                // 判断跟服务器的连接状态。如果是200，则说明连接正常，服务器有响应
                if (httpConn.getResponseCode() == CommonParamUtil.INT_200) {
                    ByteArrayDataSource dataSource = new ByteArrayDataSource(urlObj.openStream(), "application/octet-stream");
                    dataSource.setName("附件文件." + extName);

                    MailAccount mailAccount = new MailAccount();
                    mailAccount.setHost(host);
                    mailAccount.setPort(port);
                    mailAccount.setPass(password);
                    mailAccount.setFrom(username);
                    mailAccount.setSslEnable(true);
                    mailAccount.setSocketFactoryClass(socketFactoryClass);

                    Mail.create(mailAccount)
                            .to(target)
                            .setCharset(Charsets.UTF_8)
                            .setAttachments(dataSource)
                            .setTitle(title)
                            .setContent(content)
                            .send();
                }
            }
            catch (Exception e) {
                ExUtil.throwEx("网络文件获取异常：" + e.getMessage());
            }
            finally {
                httpConn.disconnect();
            }
        });
    }
}
